package org.example.MedicalCrowdsourcing.repository;

import org.example.MedicalCrowdsourcing.model.entity.Permission;
import org.example.MedicalCrowdsourcing.model.entity.Role;
import org.example.MedicalCrowdsourcing.model.entity.RolePermission;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface RolePermissionRepository extends JpaRepository<RolePermission, Long> {
    List<RolePermission> findByRole(Role role);
    
    List<RolePermission> findByPermission(Permission permission);
    
    Optional<RolePermission> findByRoleAndPermission(Role role, Permission permission);
    
    boolean existsByRoleAndPermission(Role role, Permission permission);
    
    @Query("SELECT rp.permission FROM RolePermission rp WHERE rp.role.id = :roleId")
    List<Permission> findPermissionsByRoleId(@Param("roleId") Integer roleId);
    
    @Query("SELECT CASE WHEN COUNT(rp) > 0 THEN true ELSE false END FROM RolePermission rp " +
           "WHERE rp.role.id = :roleId AND rp.permission.name = :permissionName")
    boolean hasPermission(@Param("roleId") Integer roleId, @Param("permissionName") String permissionName);
} 